import csv
import os
medicine = []
prescription_str = []
ans_str = []
csvdata = []
output_str = []
def read_medData(path):
    with open(path) as file:
        reader = csv.DictReader(file)
        for row in reader:
            medicine.append(row['name_str'])
            prescription_str.append(row['prescription_str'])
        file.seek(0)
        print(csvdata)
    os.system('cls')
    print("Read name data successfully")

def get_surrounding_chars_with_markdown(pinyin_str: str, index: int, length: int, link: str = "https://example.com") -> str:
    # 确保索引和长度不会越界
    if index < 0 or length < 0 or index > len(pinyin_str) - 1:
        raise ValueError("Index or length is out of bounds.")
    
    # 计算需要替换的字符片段的起始和结束位置
    char_start = index
    char_end = min(index + length, len(pinyin_str))  # 确保不会超出字符串长度
    
    # 获取指定长度的字符片段
    chars_to_replace = pinyin_str[char_start:char_end]
    
    # 用 Markdown 格式替换指定索引处的字符片段
    markdown_format = f"[{chars_to_replace}]({link})"
    
    # 将整个字符串中的指定字符片段替换为 Markdown 链接形式
    modified_str = pinyin_str[:char_start] + markdown_format + pinyin_str[char_end:]
    
    return modified_str

""" ans:岩参，悦姐的岩参（str），悦姐的悦姐的岩参 """
def add_link(ans_str:list,ans_pos:list,str:str,index:int):
    canAdd = True
    for i,item in enumerate(ans_str):
        posistion = str.find(item)
        if posistion == -1:
            continue
        else:
            if ans_pos[i] != index:
                continue
            else:
                ans_str[i] = str
                ans_pos[i] = index
                canAdd = False
    if canAdd:
        ans_str.append(str)
        ans_pos.append(index)


def match_csv_data(key):
    for i,keyword in enumerate(prescription_str):
        is_success = False
        keyword: str
        ans_str = []
        ans_pos = []
        success_name = ''
        success_med_position = 0
        for j,item in enumerate(medicine):
            if i == j:
                continue
            position = keyword.find(item)
            if (position != -1):
                is_success = True
                """ ans.append(item) """
                add_link(ans_str,ans_pos,item,j)

        if is_success:
            print(f"Found {i} '(被匹配药方){medicine[success_med_position]}' → '{success_name}(匹配名词)',")
            """ print(f"ans:{get_surrounding_chars_with_markdown(keyword,position,len(success_name),5)}") """
            print(ans_str,ans_pos)
            
            str_buffer = keyword
            for k,link_str in enumerate(ans_str):
                str_buffer = get_surrounding_chars_with_markdown(str_buffer,str_buffer.find(link_str),len(link_str),ans_pos[k])
            output_str.append(str_buffer)
            print('\n')

def write_csv():
    with open('output.csv', mode='w', encoding='utf-8',newline='\n') as file:
        writer = csv.writer(file)
        for item in output_str:
            writer.writerow([item])

read_medData('datatest.csv')
match_csv_data('')
write_csv()

"""
匹配文本：111222
会被：11 1 111匹配到
11
"""

